package com.jhws.core.shiro.filter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import com.jhws.common.base.bo.JsonRespData;
import com.jhws.core.shiro.service.IOAuthService;
import com.jhws.util.LogHelper;
import com.jhws.util.jsonUtil;

/**
 * @author : Alex Tan
 * @description: 对rest api进行拦截，判断Authorization头部，头部格式为username-token
 */
public class RestApiFilter extends PathMatchingFilter{

	@Resource
	private IOAuthService IOAuthService;
	
	@Override
	protected boolean onPreHandle(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		// TODO Auto-generated method stub
		String AuthStr = WebUtils.toHttp(request).getHeader("Authorization");
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
		
		if(AuthStr == null){
			WebUtils.toHttp(response).setStatus(HttpStatus.UNAUTHORIZED.value());
			response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -1, "无Authorization信息")));
			return false;
		}
		
		String [] userToken = AuthStr.split("-");
		
		if(userToken.length == 2) {
			String username = IOAuthService.getUsernameByAccessToken(userToken[1]);

			if(!userToken[0].equals(username)){
				LogHelper.getLogger().debug("token invalid");
				WebUtils.toHttp(response).setStatus(HttpStatus.UNAUTHORIZED.value());
				response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -2, "无效token")));
				return false;
			}
			else
				LogHelper.getLogger().debug("token valid");
				
		}
		else {
			WebUtils.toHttp(response).setStatus(HttpStatus.UNAUTHORIZED.value());
			response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -3, "Authorization格式不正确")));
			return false;
		}
		return true;
	}
	
}
